package com.fancy.middleware.common.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public interface SerializerService {

    // 反序列化方法
    <T> T deserialize(Class<T> clazz, byte[] bytes);

    // 序列化方法
    <T> byte[] serialize(T object);

    enum SerializerAlgorithm implements SerializerService {
        // Java 实现
        Java {
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                try {
                    ObjectInputStream in =
                            new ObjectInputStream(new ByteArrayInputStream(bytes));
                    Object object = in.readObject();
                    return (T) object;
                } catch (IOException | ClassNotFoundException e) {
                    throw new RuntimeException("SerializerAlgorithm.Java 反序列化错误", e);
                }
            }

            @Override
            public <T> byte[] serialize(T object) {
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    new ObjectOutputStream(out).writeObject(object);
                    return out.toByteArray();
                } catch (IOException e) {
                    throw new RuntimeException("SerializerAlgorithm.Java 序列化错误", e);
                }
            }
        },
        PROTOBUF {
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                return null;
            }

            @Override
            public <T> byte[] serialize(T object) {
                return new byte[0];
            }
        };
        // 需要从协议的字节中得到是哪种序列化算法
        public static SerializerAlgorithm getSerializerAlgorithm(String value) {
            if(value == null) {
                return SerializerAlgorithm.PROTOBUF;
            }
            return SerializerAlgorithm.valueOf(value);
        }
    }
}
